/* eslint-disable */
// import "@/utils/chat/abp.signalr-client";
import abp from 'abp'

var chatHub = null;
var isChatConnected = false;

function configureConnection(connection) {
    // Set the common hub
    chatHub = connection;

    // Reconnect if hub disconnects
    connection.onclose(e => {
        isChatConnected = false;
        if (e) {
            abp.log.debug('Chat connection closed with error: ' + e);
        } else {
            abp.log.debug('Chat disconnected');
        }

        if (!abp.signalr.autoConnect) {
            return;
        }

        setTimeout(() => {
            connection.start().then(result => {
                isChatConnected = true;
            });
        }, 5000);
    });

    // Register to get notifications
    registerChatEvents(connection);
}

function registerChatEvents(connection) {
    connection.on('getChatMessage', message => {
        abp.event.trigger('app.chat.messageReceived', message);
    });

    connection.on('getUserConnectNotification', (friend, isConnected) => {
        abp.event.trigger('app.chat.userConnectionStateChanged',
            {
                friend: friend,
                isConnected: isConnected
            });
    });

    connection.on('getallUnreadMessagesOfUserRead', friend => {
        abp.event.trigger('app.chat.allUnreadMessagesOfUserRead',
            {
                friend: friend
            });
    });

    connection.on('getReadStateChange', friend => {
        abp.event.trigger('app.chat.readStateChange',
            {
                friend: friend
            });
    });
}

export function sendMessage(messageData, callback) {
    if (!isChatConnected) {
        if (callback) {
            callback();
        }

        abp.notify.warn("ChatIsNotConnectedWarning");
        return;
    }

    chatHub.invoke('sendMessage', messageData).then(result => {
        if (result) {
            abp.notify.warn(result);
        }

        if (callback) {
            callback();
        }
    }).catch(error => {
        abp.log.error(error);

        if (callback) {
            callback();
        }
    });
}

export function init() {
    abp.signalr.connect();
    abp.signalr.startConnection(abp.appPath + 'signalr-chat', connection => {
        abp.event.trigger('app.chat.connected');
        isChatConnected = true;
        configureConnection(connection);
    });
}
